/****************************************************************************
Copyright (c) 2015-2016 Chukong Technologies Inc.
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
 
http://www.cocos2d-x.org

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
package org.cocos2dx.javascript;
import org.cocos2dx.fanpaiji.R;
import org.cocos2dx.lib.Cocos2dxActivity;
import org.cocos2dx.lib.Cocos2dxGLSurfaceView;
import com.cf.msc.sdk.AppVest;
import com.cf.msc.sdk.SecurityConnection;

import android.annotation.SuppressLint;
import android.graphics.drawable.Drawable;
import android.os.Bundle;

import android.content.Intent;
import android.content.res.Configuration;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.WindowManager;

import android.content.ClipboardManager;
import android.content.ClipData;

import org.cocos2dx.utils.NativeHelper;

import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXImageObject;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXTextObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.cocos2dx.lib.Cocos2dxJavascriptJavaBridge;
import org.json.JSONObject;
import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Environment;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import android.content.ActivityNotFoundException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import java.io.ByteArrayOutputStream;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;
import android.provider.MediaStore;
import android.net.Uri;

import java.io.UnsupportedEncodingException;
import java.util.List;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import android.content.pm.PackageInfo;

import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;

public class AppActivity extends Cocos2dxActivity {
    public static AppActivity app;
    public static IWXAPI wxapi;
    public static final String accesskey = "ec89e67bd97e03c3ad4e6bfb0ec5f25f";
    public static final String uuid = "AyglimA74msAs/Ynqyx+4AZ+ViNzGHN+ltX01XW05KrvOzqkTTPW6/g0j3neLyfKaeA+uePpeai1tRt/Pwjt46KNQn4mHipXewHp5ezQEPQCKeoGUqiBk+cxoAzdGAOOI9mb";
    public static ClipboardManager mClipboard = null;
    public static int isOffical = 0;  //0:测试版本， 1:正式版本

    private static ImageView imageView=null;
    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE

    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        app = this;
        // Workaround in https://stackoverflow.com/questions/16283079/re-launch-of-activity-on-home-button-but-only-the-first-time/16447508
        if (!isTaskRoot()) {
            // Android launched another instance of the root activity into an existing task
            //  so just quietly finish and go away, dropping the user back into the activity
            //  at the top of the stack (ie: the last state of this task)
            // Don't need to finish it again since it's finished in super.onCreate .
            return;
        }

        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);


//        //去掉这个权限请求
//        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
//            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
//        }

//        int permission = ActivityCompat.checkSelfPermission(this,
//                Manifest.permission.WRITE_EXTERNAL_STORAGE);
//
//        if (permission != PackageManager.PERMISSION_GRANTED) {
//            // We don't have permission so prompt the user
//            ActivityCompat.requestPermissions(this, PERMISSIONS_STORAGE,REQUEST_EXTERNAL_STORAGE);
//        }

        this.initsoftkeyboard();
        if (null == mClipboard) {
            mClipboard = (ClipboardManager) getSystemService(this.CLIPBOARD_SERVICE);
        }

        // DO OTHER INITIALIZATION BELOW
        SDKWrapper.getInstance().init(this);
        Log.v("___weixin login", "0");
        NativeHelper.init(this);

        Window window = getWindow();
        WindowManager.LayoutParams params = window.getAttributes();
        params.systemUiVisibility = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION|View.SYSTEM_UI_FLAG_IMMERSIVE;
        window.setAttributes(params);

        int res = AppVest.init(accesskey,uuid);
        if (res == -1) {
           // Log.   ("MainActivity", "appvest init failed");
            return;
        }
        //设置启动页
    }
    static  public void setsoftkeoardheight(int height){
        app.setsoftkeoardheighttemp(height);
    }

    static  public void openkeyboardJs(){
        app.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Log.d("xxx", "app.keyboardview*******************************************=" );
                app.keyboardview.setVisibility(View.VISIBLE);
                app.setkeyboardVisible(true);
                app.runbottom();
            }
        });
    }
    static public void closeOnBlur(){
        Log.d("xxx", "closeOnBlur 失去焦点关闭导航条*******************************************=" );
//        app.closeeditbox();
    }
   static  public void closekeyboardJs(){
        app.closekeyboard();
    }
    @SuppressLint("ResourceType")
    void initsoftkeyboard() {
        this.keyboardview= LayoutInflater.from(this).inflate(R.layout.softketboardlayout, null);
        //Log.w(TAG, "keyboardview ***********************************!"+this.keyboardview);
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        mFrameLayout.addView(this.keyboardview,layoutParams);
        this.inputeditbox = (EditText)findViewById(R.id.editText);

        TextWatcher mTextWatcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                Drawable rewardIcon=  null;
                if(start==0  && count==0){
                    rewardIcon = ContextCompat.getDrawable(app,R.drawable.add);
                    findViewById(R.id.button3).setBackground(rewardIcon);
                }else{
                    rewardIcon = ContextCompat.getDrawable(app,R.drawable.fs);
                    findViewById(R.id.button3).setBackground(rewardIcon);
                }
            }
            @Override
            public void afterTextChanged(Editable s) {

            }
        };
       (this.inputeditbox).addTextChangedListener(mTextWatcher);

        this.inputeditbox.setOnFocusChangeListener(new android.view.View.
                OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                Drawable rewardIcon=  null;
                View view = findViewById(R.id.editText);
                if (hasFocus) {
                    // 此处为得到焦点时的处理内容
                    rewardIcon = ContextCompat.getDrawable(app,R.drawable.shurukuangxuanzhong);
                    findViewById(R.id.editText).setBackground(rewardIcon);
                    findViewById(R.id.button4).setVisibility(view.GONE);
                    //打开软键盘(输入框获得焦点)
                    app.runOnGLThread(new Runnable() {
                        @Override
                        public void run() {
                            Cocos2dxJavascriptJavaBridge.evalString("cc.vv.eventCustom.emit(\"inputHasFocus\");");
                        }
                    });
                } else {
                    // 此处为失去焦点时的处理内容
                    rewardIcon = ContextCompat.getDrawable(app,R.drawable.shurukuangditu);
                    findViewById(R.id.editText).setBackground(rewardIcon);
                }
            }
        });

        View view = findViewById(R.id.button);
        view.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent event) {
                View parent = (View)view.getParent();
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        break;
                    case MotionEvent.ACTION_MOVE:
                        break;
                    case MotionEvent.ACTION_UP:
                        Drawable rewardIcon=  null;
                       // Log.d(TAG, "tttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttt "  + app.openyuyinflag );
                        if(!app.openyuyinflag){
                            rewardIcon = ContextCompat.getDrawable(app,R.drawable.yy);
                            findViewById(R.id.button).setBackground(rewardIcon);
                            findViewById(R.id.editText).setVisibility(View.VISIBLE);
                            findViewById(R.id.button4).setVisibility(View.GONE);
                        }else{
                            rewardIcon = ContextCompat.getDrawable(app,R.drawable.jp);
                            findViewById(R.id.button).setBackground(rewardIcon);
                            findViewById(R.id.editText).setVisibility(View.GONE);
                            findViewById(R.id.button4).setVisibility(View.VISIBLE);
                        }
                        app.openyuyin();
                        break;
                }
                return false;
            }
        });

        //
        View viewbiaoqing = findViewById(R.id.button2);
        viewbiaoqing.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent event) {
                View parent = (View)view.getParent();
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        break;
                    case MotionEvent.ACTION_MOVE:
                        break;
                    case MotionEvent.ACTION_UP:
                        app.openBq();
                        break;
                }
                return false;
            }
        });
        //
        View viewvedio = findViewById(R.id.button3);
        viewvedio.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent event) {
                View parent = (View)view.getParent();
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        break;
                    case MotionEvent.ACTION_MOVE:
                        break;
                    case MotionEvent.ACTION_UP:
                        String str1="";
                        EditText editText1 =(EditText)findViewById(R.id.editText);
                        str1=editText1.getText().toString();
                        Log.e("123", "  输入框有东西  发送消息"+str1);
                        if(str1.length()>0){ //发送
                            str1 = str1.replaceAll("\n", "\\\\n"); //处理换行符号;
                            Log.e("123", "  输入框有东西  发送消息" + str1);
                            app.sendMsg(str1);
                            editText1.setText("");
                        }else{
                            Log.e("123", "  输入框 没有东西   切换    ui");
                            app.openvedio();
                        }
                        break;
                }
                return false;
            }
        });

        View viewrecord = findViewById(R.id.button4);
        viewrecord.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent event) {
                View parent = (View)view.getParent();
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        findViewById(R.id.button4).setBackground(ContextCompat.getDrawable(app,R.drawable.anzhuditu));
                        app.runOnGLThread(new Runnable() {
                            @Override
                            public void run() {
                                Cocos2dxJavascriptJavaBridge.evalString("cc.vv.eventCustom.emit(\"startrecord\");");
                            }
                        });
                        break;
                    case MotionEvent.ACTION_MOVE:
                        break;
                    case MotionEvent.ACTION_UP:
                        findViewById(R.id.button4).setBackground(ContextCompat.getDrawable(app,R.drawable.shurukuangditu));
                        app.runOnGLThread(new Runnable() {
                            @Override
                            public void run() {
                                Cocos2dxJavascriptJavaBridge.evalString("cc.vv.eventCustom.emit(\"endrecord\");");
                            }
                        });
                        break;
                }
                return false;
            }
        });

        this.closekeyboard();
    }

    public static void inputEmojy(String emojy){
        String emojiName = emojy;  //其实4个字节
        int emojiCode = Integer.valueOf(emojiName, 16);
        byte[] emojiBytes = int2bytes(emojiCode);
        String emojiChar = null;
        try {
            emojiChar = new String(emojiBytes, "utf-32");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String str1="";
        EditText editText1 =app.inputeditbox;
        str1=editText1.getText().toString();
        str1 = str1+emojiChar;
        editText1.setText(str1);
    }



    static public void photoTo(String path) {
        if (ActivityCompat.checkSelfPermission(app,
                Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(app, new String[] { Manifest.permission.READ_EXTERNAL_STORAGE }, 1);
        }
        Bitmap bmp = BitmapFactory.decodeFile(path);
        app.savePhoto(bmp);
    }

    /**
     * @param bmp 获取的bitmap数据
     */
    public void savePhoto(Bitmap bmp) {

        String picName = System.currentTimeMillis() + "hh";

        String fileName = null;
        // 系统相册目录
        String galleryPath = Environment.getExternalStorageDirectory() + File.separator + Environment.DIRECTORY_DCIM
                + File.separator + "Camera" + File.separator;
        // 声明文件对象
        File file = null;
        // 声明输出流
        FileOutputStream outStream = null;
        System.out.println("picName" + picName);
        System.out.println("galleryPath " + galleryPath);
        try {
            // 如果有目标文件，直接获得文件对象，否则创建一个以filename为名称的文件
            file = new File(galleryPath, picName + ".jpg");

            // 获得文件相对路径
            fileName = file.toString();
            // 获得输出流，如果文件中有内容，追加内容
        } catch (Exception e) {
            e.getStackTrace();
        }
        MediaStore.Images.Media.insertImage(app.getContentResolver(), bmp, fileName, null);
        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        Uri uri = Uri.fromFile(file);
        intent.setData(uri);
        app.sendBroadcast(intent);
    }

    static public boolean checkInstall(String packNam) {
        final PackageManager packageManager = app.getPackageManager();
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (pn.equals(packNam)) {
                    return true;
                }
            }
        }
        return false;
    }

    public static void copyFile(String oldPath, String newPath) {
        try {
            int bytesum = 0;
            int byteread = 0;
            File oldfile = new File(oldPath);
            if (oldfile.exists()) {
                InputStream inStream = new FileInputStream(oldPath);
                FileOutputStream fs = new FileOutputStream(newPath);
                byte[] buffer = new byte[1024];
                while ((byteread = inStream.read(buffer)) != -1) {
                    bytesum += byteread;
                    fs.write(buffer, 0, byteread);
                }
                oldfile.delete();
                inStream.close();
                fs.close();
            }
        } catch (Exception e) {
        }
    }

    public static byte[] bmpToByteArray(final Bitmap bmp, final boolean needRecycle) {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.PNG, 100, output);
        if (needRecycle) {
            bmp.recycle();
        }
        byte[] result = output.toByteArray();
        try {
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    static public void registerQQWithAppid(String appid) {

    }

    public static final int WX_SHARE_TEXT = 0;
    public static final int WX_SHARE_IMG = 1;
    public static final int WX_SHARE_MUSIC = 2;
    public static final int WX_SHARE_VIDEO = 3;
    public static final int WX_SHARE_WEB_PAGE = 4;

    private String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
    }
    static public void registerWeChatWithAppid(String appid) {
        app.createWXAPI(appid);
    }
    /**
     * 微信相关
     */
    static public void jumpToWX() {
        app.jumpWX();
    }

    private void jumpWX() {
        try {
            Intent intent = getPackageManager().getLaunchIntentForPackage("com.tencent.mm");
            startActivity(intent);
        } catch (ActivityNotFoundException e) {
            Toast.makeText(app, "没有安装微信", Toast.LENGTH_LONG).show();
        }
    }

    private void createWXAPI(String appid) {
        wxapi = WXAPIFactory.createWXAPI(this, appid, true);
        wxapi.registerApp(appid);
        System.out.println("-----------注册微信成功,appid=" + appid);
    }

    private boolean ifWxInstalled() {
        if (!wxapi.isWXAppInstalled()) {
            app.runOnGLThread(new Runnable() {
                @Override
                public void run() {
                    Cocos2dxJavascriptJavaBridge.evalString("cc.vv.GLUtils.showTips(\"请先下载安装微信\");");
                }
            });
            return false;
        } else {
            return true;
        }
    }
    private void wxShare(String reqContent) {
        // 判断客户端是否安装了微信
        if (!ifWxInstalled()) {
            return;
        }
        try {
            JSONObject reqContentJSON = new JSONObject(reqContent);
            int type = reqContentJSON.getInt("type");
            int scene = reqContentJSON.getInt("scene");
            String title = reqContentJSON.getString("title");
            String description = reqContentJSON.getString("description");
            String content = reqContentJSON.getString("content");

            WXMediaMessage msg = new WXMediaMessage();

            switch (type) {
                // 文本
                case WX_SHARE_TEXT:
                    WXTextObject textObj = new WXTextObject();
                    textObj.text = content;
                    msg.title = title;
                    msg.mediaObject = textObj;
                    msg.description = description;
                    break;
                // 图片
                case WX_SHARE_IMG:
                    if (ActivityCompat.checkSelfPermission(app,
                            Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                        ActivityCompat.requestPermissions(app, new String[] { Manifest.permission.READ_EXTERNAL_STORAGE },
                                1);
                    }
                    // 初始化WXImageObject对象
                    Bitmap bmp = BitmapFactory.decodeFile(content);
                    WXImageObject imgObj = new WXImageObject(bmp);
                    // 初始化WXMediaMessage对象
                    msg.mediaObject = imgObj;
                    // 设置缩略图
                    Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp, 150, 150, true);
                    bmp.recycle();
                    msg.thumbData = bmpToByteArray(thumbBmp, true);

                    //copy to camara
                    String res="qrnode.jpg";
                    String strDestFile = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + res;
                    copyFile(content, strDestFile);

                    break;
                // // 音乐
                // case WX_SHARE_MUSIC:
                // WXMusicObject music = new WXMusicObject();
                // music.musicUrl = content;

                // msg.mediaObject = music;
                // msg.title = title;
                // msg.description = description;
                // break;
                // // 视频
                // case WX_SHARE_VIDEO:
                // WXVideoObject video = new WXVideoObject();
                // video.videoUrl = content;

                // msg = new WXMediaMessage(video);
                // msg.title = title;
                // msg.description = description;
                // break;
                // // 网页
                // case WX_SHARE_WEB_PAGE:
                // WXWebpageObject webpage = new WXWebpageObject();
                // webpage.webpageUrl = content;

                // msg = new WXMediaMessage(webpage);
                // msg.title = title;
                // msg.description = description;
                // break;
                default:
                    break;
            }

            SendMessageToWX.Req req = new SendMessageToWX.Req();
            req.transaction = buildTransaction(type + "");
            req.message = msg;
            req.scene = scene;

            // 调用api接口，发送数据到微信
            wxapi.sendReq(req);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    static public void sendWxShareRequest(String reqContent) {
        app.wxShare(reqContent);
    }

    /**
     * 分享回调js
     *
     * @param msg
     */
    static public void onShared(String msg) {
        final String tips = msg;
        app.runOnGLThread(new Runnable() {
            @Override
            public void run() {
                Cocos2dxJavascriptJavaBridge.evalString("cc.vv.wxChatMgr.onShared(\"" + tips + "\");");
            }
        });
    }
    /**
     * 微信登录接口
     * 请求CODE
     */

    static public void sendWxAuthRequest(String reqState){
        app.sendAuthRequest(reqState);
    }
    /**
     * 发起授权请求
     * @param reqState
     */
    private void sendAuthRequest(String reqState) {
        //判断客户端是否安装了微信
        if(!ifWxInstalled()){
            return;
        }
        SendAuth.Req req = new SendAuth.Req();
        req.scope = "snsapi_userinfo";
        req.state = reqState;
        wxapi.sendReq(req);
    }

    /**
     * 授权回调js
     * @param code
     */
    static public void onGetAuth(String code, String state) {
        final String codes = code;
        final String states = state;
        app.runOnGLThread(new Runnable() {
            @Override
            public void run() {
                System.out.println("-----------souquan,appid=" );
                Cocos2dxJavascriptJavaBridge.evalString("cc.vv.wxChatMgr.onGetWxAuth(\""+codes+"\",\""+states+"\");");
                System.out.println("-----------souquan,appid111=" );
            }
        });
    }

    public ImageView createLogoImg() {
        imageView = new ImageView(this);
        //imageView.setImageResource(R.drawable.splash);

        imageView.setScaleType(ImageView.ScaleType.FIT_XY );
        return imageView;
    }
    @Override
    public Cocos2dxGLSurfaceView onCreateView() {
        Cocos2dxGLSurfaceView glSurfaceView = new Cocos2dxGLSurfaceView(this);

        glSurfaceView.setEGLConfigChooser(5, 6, 5, 0, 16, 8);
        SDKWrapper.getInstance().setGLSurfaceView(glSurfaceView, this);

        return glSurfaceView;
    }

    @Override
    protected void onResume() {
        super.onResume();
        SDKWrapper.getInstance().onResume();

    }

    @Override
    protected void onPause() {
        super.onPause();
        SDKWrapper.getInstance().onPause();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        SDKWrapper.getInstance().onDestroy();

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        SDKWrapper.getInstance().onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        SDKWrapper.getInstance().onNewIntent(intent);
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        SDKWrapper.getInstance().onRestart();
    }

    @Override
    protected void onStop() {
        super.onStop();
        SDKWrapper.getInstance().onStop();
    }
        
    @Override
    public void onBackPressed() {
        SDKWrapper.getInstance().onBackPressed();
        super.onBackPressed();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        SDKWrapper.getInstance().onConfigurationChanged(newConfig);
        super.onConfigurationChanged(newConfig);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        SDKWrapper.getInstance().onRestoreInstanceState(savedInstanceState);
        super.onRestoreInstanceState(savedInstanceState);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        SDKWrapper.getInstance().onSaveInstanceState(outState);
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onStart() {
        SDKWrapper.getInstance().onStart();
        super.onStart();
    }

    //申请权限的回调
    @Override
    public void onRequestPermissionsResult(int requestCode,  String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode){//
            case 0://如果申请权限回调的参数
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(this,"申请成功",Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(this,"拒绝权限",Toast.LENGTH_SHORT).show();
                }
                break;

        }

    }

    public static void copyMsgToClipBoard(String msg){
        if (mClipboard != null) {
            ClipData textCd = ClipData.newPlainText("", msg);
            mClipboard.setPrimaryClip(textCd);
        }
    }

    public static void CopyStrtoClipboard( String str) {
        ClipData mClipData = ClipData.newPlainText("Label", str);
        mClipboard.setPrimaryClip(mClipData);
    }
//
    public static String pasteFromClipboard() {
        String getMsg = "";
        if (!mClipboard.hasPrimaryClip()) {
            return getMsg;
        }
        ClipData clipData = mClipboard.getPrimaryClip();
        ClipData.Item item = clipData.getItemAt(0);
        if(item != null && item.getText() != null){
            CharSequence str = item.getText().toString();
            getMsg += str;
            Log.i("cocos", "getMsg FromClipboard is  : " + getMsg);
        }
        return getMsg;
    }

    public static int getVersionType() {
        return isOffical;
    }

    public static String getServerIpAndPort(String ip, int port){

        SecurityConnection conn = AppVest.getServerIPAndPort(ip, port);
        if (conn.getServerPort() == -1) {
            return"";
        }

        Map<String, String> map = new HashMap<String, String>();
        map.put("ip", conn.getServerIp());
        map.put("port", conn.getServerPort()+"");
        JSONObject jObject = new JSONObject(map);
        return jObject.toString();

       // final String fun = funName + "(" + jObject.toString() + ")";
       // Cocos2dxJavascriptJavaBridge.evalString(fun);
    }
    public static String getClientIp() {
        String client_ip = AppVest.getClientIP();
        return client_ip;
    }

}
